type Storage = {
  set: <T>(key: string, val: T) => boolean;
  get: <T>(key: string) => T | null;
  remove: (key: string) => boolean;
  clear: () => boolean;
};

type IDB = {
  LS: Storage;
  SS: Storage;
};

const DB: IDB = {
  LS: {
    set: (key, val) => {
      if (!key || !localStorage) return false;
      try {
        localStorage.setItem(key, JSON.stringify(val));
        return true;
      } catch (error) {
        return false;
      }
    },
    get: (key) => {
      if (!key || !localStorage) return null;
      try {
        const val = localStorage.getItem(key);
        if (val) return JSON.parse(val);
        return null;
      } catch (error) {
        return null;
      }
    },
    remove: (key) => {
      if (!key || !localStorage) return false;
      localStorage.removeItem(key);
      return true;
    },
    clear: () => {
      if (!localStorage) return false;
      try {
        localStorage.clear();
        return true;
      } catch (error) {
        return false;
      }
    },
  },
  SS: {
    set: (key, val) => {
      if (!key || !sessionStorage) return false;
      try {
        sessionStorage.setItem(key, JSON.stringify(val));
        return true;
      } catch (error) {
        return false;
      }
    },
    get: (key) => {
      if (!key || !sessionStorage) return null;
      try {
        const val = sessionStorage.getItem(key);
        if (val) return JSON.parse(val);
        return null;
      } catch (error) {
        return null;
      }
    },
    remove: (key) => {
      if (!key || !sessionStorage) return false;
      sessionStorage.removeItem(key);
      return true;
    },
    clear: () => {
      if (!sessionStorage) return false;
      try {
        sessionStorage.clear();
        return true;
      } catch (error) {
        return false;
      }
    },
  },
};

export default DB;
